import entities, stats, wish, reservation
from google.appengine.api import memcache

def getById(user_id):
    
    user = entities.User.all().filter("user_id = ", user_id).get()
        
    return user

def getByUID(uid):
    
    key = entities.db.Key.from_path("User", uid)
        
    return entities.db.get(key)

def create(user_id, name = ""):
    
    user = getById(user_id)
    
    if user != None: return False
    
    user = entities.User(user_id = user_id, name = name)
    
    user.put()
    
    stats.increment(users = True)
    
    return True

def setName(user_id, name = ""):
    
    user = getById(user_id)
    
    # user does not exists
    if user == None: return create(user_id, name)
    
    # username is the same
    if user.name == name: return True
    
    user.name = name
    
    user.put()
    
    return True

def remove(user_id):
    
    user = getById(user_id)
    
    if user == None: return False
    
    user.delete()
    
    wishes = wish.listByUser(user_id)
    
    for item in wishes: item.delete()
    
    mc_key = "ws/u/0/" + user_id
    data = memcache.delete(mc_key)
    
    reservs = reservation.listByUser(user_id)
    
    for item in reservs: item.delete()
    
    return True

def invite(user_id, users):
    
    stats.increment(invites = True, count = len(users))
    increment(user_id, invites = True, count = len(users))
    
    return True

def increment(user_id, wishes = False, reservations = False, invites = False, count = 1):
    
    user = getById(user_id)
    
    if user == None: user = entities.User(user_id = user_id)
    
    if wishes: user.ws_count = user.ws_count + count
    if reservations: user.rs_count = user.rs_count + count
    if invites: user.inv_count = user.inv_count + count
    
    user.put()

def decrement(user_id, wishes = False, reservations = False):
    
    user = getById(user_id)
    
    if user == None: return
    
    if wishes and user.ws_count > 0: user.ws_count = user.ws_count - 1
    if reservations and user.rs_count > 0: user.rs_count = user.rs_count - 1
    
    user.put()